/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: Frank
 * 系统版本: 1.0.0
 * 开发人员: Frank
 * 开发时间: 2019/9/19 14:45
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.job.web.controller;

import com.codahale.metrics.annotation.Timed;
import com.spring.arch.job.dto.JobParam;
import com.spring.arch.job.model.JobInfo;
import com.spring.arch.job.service.JobInfoService;
import com.spring.arch.common.dto.result.ListResultDTO;
import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.job.dto.JobParam;
import com.spring.arch.job.model.JobInfo;
import com.spring.arch.job.service.JobInfoService;
import com.spring.arch.job.web.converter.JobInfoConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 任务控制器
 * @author Frank
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@Slf4j
@RestController
@RequestMapping(value = "/job/w/task", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(tags = {"Web端任务Api"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TaskController {

    private final JobInfoService jobInfoService;
    private final JobInfoConverter jobInfoConverter;

    @Autowired
    public TaskController(JobInfoService jobInfoService,
                          JobInfoConverter jobInfoConverter) {
        this.jobInfoService = jobInfoService;
        this.jobInfoConverter = jobInfoConverter;
    }

    /**
     * 批量创建任务
     * @param jobParams 任务参数集合
     * @return 任务id集合
     */
    @Timed
    @ApiOperation(value = "新建操作")
    @RequestMapping(value = "/batchSave", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
    public ListResultDTO<Integer> create(@RequestBody @Valid final List<JobParam> jobParams) {
        List<JobInfo> models = jobInfoConverter.jobParamsToModelList(jobParams);
        List<Integer> jobIds = jobInfoService.saveAll(models);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was created.", JobInfo.class.getSimpleName(), jobIds);
        }
        return ListResultDTO.success(jobIds);
    }

    /**
     * 批量删除任务
     * @param jobIds 任务ids
     * @return 执行结果
     */
    @Timed
    @ApiOperation(value = "删除操作")
    @RequestMapping(value = "delete", method = RequestMethod.DELETE, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResultDTO<Void> delete(@RequestParam @Valid final List<Integer> jobIds) {
        jobInfoService.deleteAll(jobIds);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was disable.", JobInfo.class.getSimpleName(), jobIds);
        }
        return ResultDTO.success();
    }
}
